import socket
import sys

#create a tcp/ip socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#bind the socket to the port.
server_name = socket.gethostname()
SERVERaddr = (server_name,10000)
print('开始监听于{}主机，端口{}'.format(*SERVERaddr))
sock.bind(SERVERaddr)

#监听消息
sock.listen(1)

while True:
    #等待连接
    print('等待连接')
    connection,client_addr = sock.accept()
    try:
        print('连接开始！来自',client_addr)

        #返回消息
        while True:
            data = connection.recv(16)
            print('返回{!r}'.format(data))
            if data:
                print('返回消息至客户端')
                connection.sendall(data)
            else:
                print('无信息',client_addr)
                break

    finally:
        #停止连接
        connection.close()


